package com.ceba.test.modules.signvisual.logicService.custom;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ceba.base.utils.IDSFileUtils;
import com.ceba.base.utils.ToPdfUtils;
import com.ceba.test.base.config.LogicPathUtil;
import com.ceba.test.base.constants.CustomStampConstants;
import com.ceba.test.modules.storage.logicService.StorageFileCacheManage;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.alibaba.fastjson.JSON;
import com.ceba.test.base.entity.PdfImage;
import com.ceba.test.base.entity.SignPrintPDF;
import com.ceba.test.base.enums.ImageFormatEnum;
import com.ceba.test.base.language.ResourceUtils;
import com.ceba.test.modules.admin.entity.GStamp;
import com.ceba.test.modules.admin.helper.GStampHelper;
import com.ceba.test.modules.filemanage.logicService.FileManageLogicService;

import configs.context.SpringBeans;


public class CustomStampSignLogicService{
	
	private FileManageLogicService fileManageLogicService =
			SpringBeans.getFileManageLogicService("fileManageLogicService");
	
	/**
	 * 取得文件的正式路径
	 * @param fileId
	 * @param isTemplates
	 * @return
	 */
	public String getFilePath(String fileId,String isTemplates){
		Map<String,String> resultMap=fileManageLogicService.getPdfPath(fileId,isTemplates);
 		return resultMap.get("filePath");
	}
	
	
	/**
	 * 获取pdf图片fff
	 * @param pdfPath
	 * @return
	 */
	public Map<String, Object> getPdfImageList(String storageAddressId,String pdfPath){
		Map<String, Object> resultMap=new HashMap<>();
		List<PdfImage> pdfImageList=new ArrayList<>();
		long  strDate =new Date().getTime();
		resultMap.put("pdfImageList", pdfImageList);
		//1.创建储存图片的文件夹
		String imagePath= LogicPathUtil.getPhysicalTempFolder(storageAddressId)+"pdfImage"+strDate+File.separator;
		String pdfImageDir="pdfImage"+new Date().getTime()+File.separator;
		IDSFileUtils.createDir(imagePath);
		String tempFilePath=null;
		//2.生成PDF图片
		String imageFormat=ImageFormatEnum.JPG.getImageFormat();
		if(!".pdf".equals(pdfPath.substring(pdfPath.lastIndexOf(".")).toLowerCase())){
			String fileName=new File(pdfPath).getName().replace(pdfPath.substring(pdfPath.lastIndexOf(".")), "");
			tempFilePath= LogicPathUtil.getPhysicalTempFolder(storageAddressId)+fileName+".pdf";
			ToPdfUtils.fileToPdf(pdfPath, tempFilePath);
		}else{
			tempFilePath=pdfPath;
		}
		ToPdfUtils.pdfToPicWithSuffix(new File(tempFilePath).getPath(),imagePath,ToPdfUtils.SCALE,imageFormat);
		Map<Integer, PdfImage> pdfImageMap=new HashMap<>();
		//3.获取所有PDF图片
		File[] files=new File(imagePath).listFiles();
		for(int i=0;i<files.length;i++){
			File file=files[i];
//			String path=file.getPath();
//			String path=CebaPathUtil.getSignPicTempPath()+pdfImageDir+file.getName();
			String path=LogicPathUtil.getBrowserPath(storageAddressId,LogicPathUtil.getVirtualPath(storageAddressId, LogicPathUtil.getPhysicalTempFolder(storageAddressId)+"pdfImage"+strDate+File.separator+file.getName()));
//			path=File.separator+CebaPathUtil.WEB_ROOT+path.split(CebaPathUtil.WEB_ROOT)[1];
			String fileInfo=file.getName().replace("."+imageFormat, "");
			String pdfName=new File(pdfPath).getName();
			PdfImage pdfImage=new PdfImage();
			
			String[] fileInfoArray=StringUtils.split(fileInfo,"_");
			pdfImage.setFileName(pdfName);
			pdfImage.setWidth(NumberUtils.toFloat(fileInfoArray[1]));
			pdfImage.setPage(fileInfoArray[0]);
			pdfImage.setHeight(NumberUtils.toFloat(fileInfoArray[2]));
			pdfImage.setZoomRate(ToPdfUtils.SCALE+"");
			pdfImage.setZoom(true);
			pdfImage.setImagePath(path.replace("\\", "/"));
			pdfImage.setId(fileInfoArray[0]);
//			Integer key=NumberUtils.toInt(file.getName().replace("."+imageFormat, ""));
			Integer key=NumberUtils.toInt(fileInfoArray[0]);
			pdfImageMap.put(key, pdfImage);
		}
		Integer mIn=-1;
		for(Integer key:pdfImageMap.keySet()){
			Integer test=key;
			for(Integer keya:pdfImageMap.keySet()){
				if(test > keya && keya > mIn){
					test=keya;
				}
			}
			mIn=test;
			pdfImageList.add(pdfImageMap.get(test));
		}
		resultMap.put("tempFilePath", tempFilePath);
		return resultMap;
	}
	
	
	
/*	*//**
	 * 获取pdf图片
	 * @param pdfPath
	 * @return
	 *//*
	public Map<String, Object> getPdfImageList(String pdfPath){
 		Map<String, Object> resultMap=new HashMap<>();
		List<PdfImage> pdfImageList=new ArrayList<>();
		resultMap.put("pdfImageList", pdfImageList);
		//1.创建储存图片的文件夹
		String pdfImageDir="pdfImage"+new Date().getTime()+File.separator;
		String imagePath=CebaPathUtil.getPhysicalTempFolder()+pdfImageDir;
		FileUtil.createDir(imagePath);
		String tempFilePath=null;
		//2.生成PDF图片
		String imageFormat=ImageFormatEnum.JPG.getImageFormat();
		if(!pdfPath.endsWith(".pdf")){
			tempFilePath= CebaPathUtil.getPhysicalTempFolder()+"out"+File.separator+ID.getGuid()+".pdf";
			ToPdfUtils.fileToPdf(pdfPath, tempFilePath);
		}else{
			tempFilePath=pdfPath;
		}
		ToPdfUtils.pdfToPic(new File(tempFilePath).getPath(),imagePath,ToPdfUtils.SCALE,imageFormat);
		Map<Integer, PdfImage> pdfImageMap=new HashMap<>();
		//3.获取所有PDF图片
		File[] files=new File(imagePath).listFiles();
		for(int i=0;i<files.length;i++){
			File file=files[i];
			String path=  CebaPathUtil.getProjectContextPath()+CebaPathUtil.getVirtualTempPath()+pdfImageDir+file.getName();
			String page=file.getName().replace("."+imageFormat, "");
			String pdfName=new File(pdfPath).getName();
			PdfImage pdfImage=new PdfImage();
			pdfImage.setFileName(pdfName);
			pdfImage.setPage(page);
			pdfImage.setZoom(true);
			pdfImage.setZoomRate(ToPdfUtils.SCALE+"");
			pdfImage.setImagePath(path.replace("\\", "/"));
			Integer key=NumberUtils.toInt(file.getName().replace("."+imageFormat, ""));
			pdfImageMap.put(key, pdfImage);
		}
		Integer mIn=-1;
		for(Integer key:pdfImageMap.keySet()){
			Integer test=key;
			for(Integer keya:pdfImageMap.keySet()){
				if(test > keya && keya > mIn){
					test=keya;
				}
			}
			mIn=test;
			pdfImageList.add(pdfImageMap.get(test));
		}
		resultMap.put("tempFilePath", tempFilePath);
		return resultMap;
	}*/
	
	
	
	/**
	 * 获取签章
	 * @return
	 */
	public List<GStamp> getCustomStampList(Map<String, Object> paramMap){
		List<GStamp> g_StampList=null;
		try {
			g_StampList = GStampHelper.getCustomStampsListByIds(paramMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return g_StampList;
	}
	
	
	
	/**
	 * 获取签章(CMA专用)
	 * @return
	 */
	public List<GStamp> getG_StampList(Map<String, Object> paramMap){
		List<GStamp> g_StampList=null;
		try {
			g_StampList = GStampHelper.getStampsListByIds(paramMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return g_StampList;
	}

	
	/**
	 * 加载PDF和签章
	 * @param g_stempIds 签章ID 字符串 用 逗号隔开
	 * @param fileId 文件ID
	 * @param isTemplates 是否是模板文件，还是报告文件
	 * @return
	 */
	public String loadPDFandSign(String g_stempIds,String fileId,String isTemplates ){
		Map<String, Object> map=new HashMap<String,Object>();
		Map<String, Object> paramMap=new HashMap<>();
		paramMap.put("g_stempIds", g_stempIds);
		List<GStamp> g_StampList=getCustomStampList(paramMap);
		
		if(CollectionUtils.isEmpty(g_StampList)){
			return ResourceUtils.getMessage("MODULES_PLEASE_CONFIGURE_PERSONAL_CHAPTER_BACKGROUND");
		}
		
		map.put(CustomStampConstants.G_STAMPLIST, g_StampList);
		Map<String,String> fileMap= fileManageLogicService.getPdfPath(fileId,isTemplates);
		String pdfPath=fileMap.get("filePath");
 		Map<String,Object> resultMap=getPdfImageList(StorageFileCacheManage.getSystemUseAddressId(),pdfPath);
 		int totalPageCount=ToPdfUtils.getPagesOfPdf(pdfPath);
		map.put(CustomStampConstants.PDFIMAGELIST, (List<PdfImage>)resultMap.get("pdfImageList"));
		//TODO 根据实际情况而定
		map.put(CustomStampConstants.PDFNAME,fileMap.get("fileName"));
		String fileName=fileMap.get("fileName");
		String result=null;
		
		if(StringUtils.isNotBlank(fileName) &&  fileName.length()>15){
			result=fileName.substring(0, 15)+"...";
		}
		
		map.put("pdfNameStr", result);
		map.put("fileId",fileMap.get("fileId"));
		//总页码数
		map.put("totalPageCount",totalPageCount);
		map.put("signFilePath", ObjectUtils.toString(resultMap.get("tempFilePath")));
		map.put("isTemplates", isTemplates);
		return JSON.toJSONString(map);
	}



	/**
	 * signPrintPdf转换为g_stamp
	 * @param signPrintPDF
	 * @return
	 */
	public GStamp signPrintPDFToG_Stamp(GStamp g_stamp,SignPrintPDF signPrintPDF){
		g_stamp.setId(signPrintPDF.getId());
		g_stamp.setUserId(signPrintPDF.getUserid());
		g_stamp.setStamp_x(signPrintPDF.getPdf_x());
		g_stamp.setStampPage(signPrintPDF.getPage());	
		g_stamp.setStamp_y(signPrintPDF.getPdf_y());
		float imgWidth=0,imgHeight=0;
		if(!signPrintPDF.getIsZoomRate()){
			imgWidth = signPrintPDF.getImageWidth()*NumberUtils.toFloat(signPrintPDF.getZoomRate(),1);
			imgHeight = signPrintPDF.getImageHeight()*NumberUtils.toFloat(signPrintPDF.getZoomRate(),1);
		}else{
			imgWidth = signPrintPDF.getImageWidth();
			imgHeight = signPrintPDF.getImageHeight();
		}
		g_stamp.setImgHeight(ObjectUtils.toString(imgHeight));
		g_stamp.setImgWidth(ObjectUtils.toString(imgWidth));
		g_stamp.setFilePath(signPrintPDF.getImagePath());
		return g_stamp;
	}
	/**
	 * 添加数据
	 * @param g_StampMap
	 * @param key
	 * @param g_Stamp
	 */
	private void addMapList(Map<String,List<GStamp>> g_StampMap,String key,GStamp g_Stamp){
		if(g_Stamp == null) return ;
		if(CollectionUtils.isEmpty(g_StampMap.get(key))){
			g_StampMap.put(key, new ArrayList<GStamp>());
		}
		g_StampMap.get(key).add(g_Stamp);
	}
	
	
	
}
